package com.xxh.kfc.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.RandomUtil;
import com.xxh.kfc.dao.OrderdetailDao;
import com.xxh.kfc.dao.OrdersDao;
import com.xxh.kfc.entity.Orderdetail;
import com.xxh.kfc.entity.Orders;
import com.xxh.kfc.service.OrderService;
import com.xxh.kfc.utils.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;

public class OrderServiceImpl  implements OrderService {
    //引入dao层

    //下单操作
    @Override
    public void addOrder(int uid, HashMap<Integer,Integer> foodIDNumMap, double totalPrice) {


        //引入dao
        SqlSession sqlSession = MyBatisUtils.getSqlSession();
        OrdersDao ordersDao = sqlSession.getMapper(OrdersDao.class);
        OrderdetailDao orderdetailDao = sqlSession.getMapper(OrderdetailDao.class);

        //生成一条order记录
        Orders order = new Orders();
        DateTime date = DateUtil.date();
        order.setOrdertime(date);
        order.setUid(uid);
        order.setPrice(BigDecimal.valueOf(totalPrice));
        //拿到当前时间
        String now = DateUtil.today();
        //转为指定的格式
        String parseStr = now.replace("-", "");
        String orderno = parseStr + uid;
        //生成10以内随机数
        for (int i = 0; i < 4; i++) {
            int anInt = RandomUtil.randomInt(10);
            orderno += anInt;
        }
        order.setOrderno(orderno);
        order.setStatus(1);
        //插入后返回订单表的ID
        ordersDao.insert(order);
        int orderID=order.getId();

        //构造订单详情
        for(Integer foodID:foodIDNumMap.keySet()){
            Orderdetail orderdetail = new Orderdetail();
            orderdetail.setOid(orderID);
            //key是foodID
            orderdetail.setFid(foodID);
            //value是订单的数目
            orderdetail.setOrdnum(foodIDNumMap.get(foodID));
            orderdetailDao.insert(orderdetail);
        }

        //提交请求，不提交插不进去数据
        sqlSession.commit();
        sqlSession.close();
    }
}
